package pgcoins

import (
	"context"
	"gitee.com/bobo-rs/creative-framework/pkg/sredis"
	"gitee.com/bobo-rs/creative-framework/pkg/utils"
	"gitee.com/bobo-rs/innovideo-services/consts"
	"gitee.com/bobo-rs/innovideo-services/framework/model"
	"gitee.com/bobo-rs/innovideo-services/framework/service"
	"gitee.com/bobo-rs/innovideo-services/library/exception"
	"gitee.com/bobo-rs/innovideo-services/library/services/safety"
	"gitee.com/bobo-rs/innovideo-services/library/tools"
	"strconv"
)

// PGCRechargeTryLockFunc 盘古币充值锁
func (c *sPgCoins) PGCRechargeTryLockFunc(ctx context.Context, uid uint, f func(ctx context.Context) error) error {
	cacheKey := tools.CacheKey(consts.PGCUserRechargeFreqLock, strconv.Itoa(int(uid)))
	// 执行程序
	_, err := safety.New().UserActionFreqTryLockFunc(ctx, cacheKey, func(ctx context.Context) (interface{}, error) {
		return nil, f(ctx)
	})
	return err
}

// ValidatorRechargeRule 验证盘古币安全充值规则
func (c *sPgCoins) ValidatorRechargeRule(ctx context.Context, uid uint, in model.PGCoinRechargeInput) (config *model.PGCConfigItem, err error) {
	// 获取配置
	config, err = service.PgCoin().Config(ctx)
	if err != nil {
		return nil, err
	}

	// 盘古币充值量
	if config.PGCRechargeMin > in.RechargePGC {
		return nil, exception.Newf(`盘古币每次充值不能小于%d`, config.PGCRechargeMin)
	}

	// 缓存KEY
	cacheKey := tools.CacheKey(consts.PGCUserTodayRechargeLock, strconv.Itoa(int(uid)))
	contains, err := sredis.NewCache().Contains(ctx, cacheKey)
	if err != nil {
		return nil, err
	}

	// 是否存在
	if contains {
		return nil, exception.Newf(`您今日充值订单超过%d笔未支付，请完成支付！`, config.PGCRechargeLimit)
	}

	// 获取今日充值未支付订单数量
	total := service.PgCoin().TodayUserRechargeCount(ctx, false)
	if config.PGCRechargeLimit <= uint(total) {
		_ = sredis.NewCache().Set(ctx, cacheKey, total, utils.ToDayZeroDiff())
		return nil, exception.Newf(`您今日充值订单超过%d笔未支付，请完成支付！`, total)
	}

	return
}

// RemoveTodayRechargeLock 移除今日充值锁定
func (c *sPgCoins) RemoveTodayRechargeLock(ctx context.Context, uid uint) error {
	_, err := sredis.NewCache().Remove(ctx, tools.CacheKey(consts.PGCUserTodayRechargeLock, strconv.Itoa(int(uid))))
	return err
}
